package com.ld.security.common.mybatis.base.service;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ld.security.common.core.base.column.ListString;
import com.ld.security.common.core.base.entity.ETreeEntity;
import com.ld.security.common.core.base.po.PagePo;
import com.ld.security.common.core.base.service.ITreeService;
import com.ld.security.common.core.base.vo.PageVo;
import com.ld.security.common.mybatis.constant.SqlCondition;
import com.ld.security.common.core.util.TreeUtil;
import com.ld.security.common.mybatis.core.wrapper.EntityWrapper;
import com.ld.security.common.mybatis.base.entity.TreeEntity;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 基本树业务实现
 *
 * @param <E>
 */

public abstract class ITreeServiceImpl<E extends ETreeEntity<E>> extends ISuperServiceImpl<E> implements ITreeService<E> {



    public List<E> findByParentPathRightLikes(List<ListString> parentpaths) {

        EntityWrapper ew = this.getWrapper();
        for (ListString parentpath : parentpaths) {
            ew.or();
            ew.addField("parentPath",SqlCondition.like_right,parentpath.getValue());
        }

        return superMapping.selectList(ew);
    }

    @Override
    public PageVo<E> getTree() {
        E root = this.newRoot();
        ListString listString =   new ListString(TreeEntity.root);
        List<E> list =this.findByParentPathRightLikes(Arrays.asList(listString));
        List<E> roots =  TreeUtil.dfsBuildTree(list);
        root.setChildren(roots);
        Page page = new Page<>();
        page.setRecords(Arrays.asList(root));
        page.setTotal(1);
        return this.toPageVo(page);
    }

    @Override
    public List<E> buildPageTree(List<E> page) {
        List<ListString> lists =  page.stream().map(val -> {
            ListString path =  new ListString();
            path.addAll(val.getParentPath());
           path.add(val.getId());
            return path;
        }).collect(Collectors.toList());

        List<E> list =  new LinkedList<>();
        list.addAll(page);

        if(!lists.isEmpty()){
            List<E>  children =  this.findByParentPathRightLikes(lists);
            list.addAll(children);
        }
        List<E> roots =  TreeUtil.dfsBuildTree(list);
        return  roots;
    }
    @Override
    public PageVo<E> pageTree(PagePo<E> po) {

        PageVo<E> page = this.page(po);
        List list =  buildPageTree(page.getList());
        page.setList(list);
        return page;
    }

    protected  E newRoot(){
        E root = this.newInstance();
        root.setId(TreeEntity.root);
        root.setLabel("根节点");
        return root;
    }



    @Override
    public void initTree(List<E> eList) {
        List<E> list =  eList.stream().flatMap(val -> {
            return TreeUtil.treeToLink(val).stream();
        }).collect(Collectors.toList());
        this.saveBatch(list);
    }
}
